package com.hbnu.server.http.handler;

import com.hbnu.enums.Status;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.*;

import java.io.File;
import java.io.FileOutputStream;

public class FileUploadHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private HttpPostRequestDecoder decoder;

    static {
        // 确保上传目录存在
        File uploadDir = new File(Status.http_SavePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        // 确保请求路径为 /up 且使用 POST 方法
        if (!"/up".equals(request.uri())) {
            sendResponse(ctx, HttpResponseStatus.NOT_FOUND, "Path not found");
            return;
        }

        if (!HttpMethod.POST.equals(request.method())) {
            sendResponse(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, "Only POST method is supported");
            return;
        }

        // 验证是否为 multipart 请求
        String contentType = request.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (contentType == null || !contentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString())) {
            sendResponse(ctx, HttpResponseStatus.BAD_REQUEST, "Unsupported content type");
            return;
        }

        // 解析 multipart 请求
        decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(true), request);

        try {
            while (decoder.hasNext()) {
                InterfaceHttpData data = decoder.next();
                if (data != null && data.getHttpDataType() == InterfaceHttpData.HttpDataType.FileUpload) {
                    FileUpload fileUpload = (FileUpload) data;
                    if (fileUpload.isCompleted()) {
                        saveFile(fileUpload); // 保存文件
                    }
                }
            }
            // 上传成功
            sendResponse(ctx, HttpResponseStatus.OK, "Files uploaded successfully!");
        } catch (HttpPostRequestDecoder.EndOfDataDecoderException e) {
            // 处理完所有数据
        } finally {
            if (decoder != null) {
                decoder.destroy(); // 清理 decoder
            }
        }
    }

    // 保存文件
    private void saveFile(FileUpload fileUpload) throws Exception {
        String fileName = fileUpload.getFilename();
        File file = new File(Status.http_SavePath+ "/" + fileName);

        try (FileOutputStream fos = new FileOutputStream(file)) {
            ByteBuf byteBuf = fileUpload.getByteBuf();
            byteBuf.readBytes(fos, byteBuf.readableBytes());
            System.out.println("File saved: " + file.getAbsolutePath());
        }
    }

    // 返回响应
    private void sendResponse(ChannelHandlerContext ctx, HttpResponseStatus status, String message) {
        String jsonResponse = String.format("{\"status\":%d,\"message\":\"%s\"}", status.code(), message);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
        response.content().writeBytes(jsonResponse.getBytes());

        // 添加 CORS 头部 没有跨域了都
       // response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
       // response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
       // response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // 允许所有域名访问
       // response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "POST, OPTIONS"); // 允许的方法
       // response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type"); // 允许的请求头

        ctx.writeAndFlush(response).addListener(future -> ctx.close());
    }

    // 异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        sendResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Server error occurred");
    }
}

